package in.abip.chisame;

import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;

public class SlideshowActivity extends Activity {
	
	private Handler _handler = new Handler();
	
	private Runnable _playing = new Runnable() {

		public void run() {
			play();
		}
		
	};
	
//	private long _startTime = 0;
	
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.slideshow_activity);
		this._handler.removeCallbacks(_playing);
//		this._startTime = System.currentTimeMillis();
		this._handler.postDelayed(_playing, 100);
	}

	private ArrayList<String> getImageFiles(File file) {
		File[] files = file.listFiles();
		ArrayList<String> filenames = new ArrayList<String>();
		String filename = "";
		try {
			for (File f : files) {
				if (f.isFile()) {
					filename = f.getAbsolutePath();
					if (filename.matches(".*(.)png|.*(.)jpg")) {
						filenames.add(filename);
					}
				}
			}
		} catch (Exception e) {
		}
		return filenames;
	}
	
	private ArrayList<String> _images = this.getImageFiles(new File("/sdcard/"));
	private int _counter = 0;
	
	public void play() {
		Log.d("debug", "Play");
		Bitmap bitmap = BitmapFactory.decodeFile(this._images.get(this._counter));
		ImageView view = (ImageView) findViewById(R.id.image);
		view.setImageBitmap(bitmap);
		view.postInvalidate();
		this._counter++;
		if (this._counter >= this._images.size()) this._counter = 0;
		this._handler.postDelayed(_playing, 3000);
	}
	
	public void show(String path) {
		Animation animation = new AlphaAnimation(0.0f, 1.0f);
		animation.setDuration(3000);
		animation.setRepeatCount(0);
		animation.setFillAfter(true);
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inPreferredConfig = Bitmap.Config.ARGB_8888;
		Bitmap bitmap = BitmapFactory.decodeFile(path, options);
		ImageView view = (ImageView) findViewById(R.id.image);
		view.setImageBitmap(bitmap);
		view.startAnimation(animation);
	}

	public void _hide() {
		Animation animation = new AlphaAnimation(1.0f, 0.0f);
		animation.setDuration(3000);
		animation.setRepeatCount(0);
		animation.setFillAfter(true);
		ImageView view = (ImageView) findViewById(R.id.image);
		view.startAnimation(animation);
	}
	
	protected void onPause() {
		super.onPause();
		this._handler.removeCallbacks(_playing);
	}
	
	protected void onResume() {
		super.onResume();
		this._handler.postDelayed(_playing, 100);
	}

}
